package cn.fjssj.demo02.controller;

import cn.fjssj.demo02.domain.ZhuZi;
import cn.fjssj.demo02.listener.ZhuZiListener;
import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

// https://juejin.cn/post/7358004857888145462?searchId=202411201434245AC398588F39C67387D9
@Slf4j
@RestController
@RequestMapping("excel")
public class SimpleExcelController {
    @Autowired
    private ZhuZiListener<ZhuZi> listener;
    // private CommonListener<ZhuZi> listener;
    @GetMapping("hello")
    public String hello(){
        return "hello";
    }

    /*
     * Excel导入接口（要解析的目标文件传入file字段）
     * */
    @PostMapping("import")
    public void excelImport(MultipartFile file) {
        if (null == file) {
            throw new RuntimeException("哎呀，网络出小差啦……");
        }
        try {
            // 从上传的文件中获取流，并基于流读取excel文件的数据
            EasyExcel.read(file.getInputStream(), ZhuZi.class,listener)
                    .sheet()
                    .doRead();
        } catch (Exception e) {
            throw new RuntimeException("Excel文件解析失败，请稍后重试~");
        }
        // 这里会获取到excel里的所有数据行，可以基于该数据进行校验、落库等业务操作
        List<ZhuZi> excelData = listener.getData();
        log.info("解析到excel数据：{}", excelData);
    }

    /**
     *  Excel导出接口（需要将response作为参数注入）
     * @param response HttpServletResponse
     */
    @GetMapping("export")
    public void excelExport(HttpServletResponse response) {
        // 内容类型也可以设置成application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "屌毛-" + System.currentTimeMillis() + ".xlsx";
        // try {
        //     // 防止中文乱码，使用URLEncoder重新编码
        //     fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        // } catch (UnsupportedEncodingException e) {
        //     throw new RuntimeException("Excel导出失败，请稍后重试");
        // }
        fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);

        // 这里模拟从库里读取的集合数据
        List<ZhuZi> zhuZis = new ArrayList<>();
        ZhuZi zhuZi1 = new ZhuZi(1L, "竹子", "男", "熊猫", new Date());
        ZhuZi zhuZi2 = new ZhuZi(2L, "屌毛", "男", "版鬓狗", new Date());
        zhuZis.add(zhuZi1);
        zhuZis.add(zhuZi2);
        // 这里指定excel数据的输出目标为响应流
        try {
            EasyExcel.write(response.getOutputStream(), ZhuZi.class).sheet("test02").doWrite(zhuZis);
        } catch (IOException e) {
            throw new RuntimeException("Excel导出失败，请稍后重试");
        }
    }
}
